<?php
class LambdaExpression {
	private $_defaultName = null;
	private $_functionCode = null;
	
	private $_functionReference;
	
	public function __construct($expression, $defaultName = '') {		
		// Split out variable name
		if (strpos($expression, '=>') !== false && strpos($expression, '$') < strpos($expression, '=>')) {
			list($defaultName, $expression) = explode('=>', $expression, 2);
		}

		// Clean expression
		$defaultName 	= trim($defaultName);
		$expression 	= trim($expression);
		
		// Convert anonymous constructors
		$expression		= str_ireplace('new {', 'new{', $expression);
		$expression		= str_ireplace('new{', '(object)array(', $expression);
		$expression		= str_ireplace('}', ')', $expression);

		$functionCode = 'return ' . $expression . ';';
		
		// Default name
		$this->_defaultName = $defaultName;
		// Function code
		$this->_functionCode = $functionCode;
			
		$this->_functionReference = create_function($defaultName, $functionCode);
	}
	
	public function execute($value) {
		if (is_array($value)) {
			return call_user_func_array($this->getFunctionReference(), $value);
		} else {
			return call_user_func($this->getFunctionReference(), $value);
		}
	}
	
	public function getDefaultName() {
		return $this->_defaultName;
	}
	
	public function getFunctionReference() {
		return $this->_functionReference;
	}
}
